    //
//  addStockInWatchList.m
//  iStock Global
//
//  Created by Andy on 2010/11/17.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "addStockInWatchList.h"
#import "DBHelper.h"

#import "AppDelegate.h"
#import "ExchangeClass.h"
#import "JSON.h"

@implementation addStockInWatchList
@synthesize delegate,AppleDeglate  ; 

#pragma mark -
#pragma mark  初始化

-(id)initWithWatchListCode:(NSMutableArray *)watchlistcode 
			 WatchListName:(NSMutableArray *)watchlistname
		  WatchListIdClass:(NSMutableArray *)watchlistid_class
			watchlistTitle:(NSString *)Title{
	self =[super init]  ;
    
    if (self ) {
		watchlist_code=watchlistcode;
		watchlist_name=watchlistname;
		watchlist_id_class=watchlistid_class;
		self.title=Title;
		 //設定
		UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
		[infoButton addTarget:self action:@selector(showSetup) forControlEvents:UIControlEventTouchUpInside];
		self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:infoButton] autorelease];
       // self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(Backup)] autorelease];        
		 		
	}
	return self;	
}
-(void)Backup{
    NSLog(@"BackUP");

}
#pragma mark -
#pragma mark  設定值初始化
-(void)Setup_DefaultValue{
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	//[prefs  boolForKey:@"Search By Name" ];
	
	//用來判斷是否有初始值
	if (![prefs objectForKey:@"Search By Name"]) {
		//無初始值
		[prefs setBool:NO forKey:@"Search By Name"];
		[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令					 
	}
	if (![prefs objectForKey:@"localize Name"]) {
		//無初始值
		[prefs setBool:YES forKey:@"localize Name"];
		[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令					 
	}	
	
    NSString *DisplayName;
    DisplayName=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]; 
    //標記:Add Target need Program    
    if ([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_ETF"]) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"ETF"];	
    } 
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_iStock Global"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"CH"];
        [all_search_country addObject:@"US"];
        [all_search_country addObject:@"HK"];
        [all_search_country addObject:@"TW"];
        [all_search_country addObject:@"KS"];
        [all_search_country addObject:@"CN"];  
        [all_search_country addObject:@"UK"];  
        [all_search_country addObject:@"SI"];   
        [all_search_country addObject:@"AX"]; 
        [all_search_country addObject:@"GR"]; 
        [all_search_country addObject:@"PA"]; 
        [all_search_country addObject:@"INDIA"];          
        [all_search_country addObject:@"IND"];  
        [all_search_country addObject:@"MI"];         
        
    }
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_HK"]  ) {
    //所有可以搜懸的國家
    all_search_country=[[NSMutableArray alloc] init];
    
    [all_search_country addObject:@"HK"];
    
    
   }
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_CH"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"CH"];
        
        
    }
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_US"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"US"];
        
        
    }        
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_UK"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"UK"];
        
        
    }   
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_CN"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"CN"];
        
        
    }       
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_KS"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"KS"];
        
        
    }          
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_iStock Global"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"CH"];
        [all_search_country addObject:@"US"];
        [all_search_country addObject:@"HK"];
        [all_search_country addObject:@"TW"];
        [all_search_country addObject:@"KS"];
        [all_search_country addObject:@"CN"];  
        [all_search_country addObject:@"UK"]; 
        [all_search_country addObject:@"SI"]; 
        [all_search_country addObject:@"AX"]; 
        [all_search_country addObject:@"GR"]; 
        [all_search_country addObject:@"PA"]; 
        [all_search_country addObject:@"INDIA"];         
        [all_search_country addObject:@"IND"]; 
        [all_search_country addObject:@"MI"];    
        [all_search_country addObject:@"NZ"];
        [all_search_country addObject:@"SA"]; 
        [all_search_country addObject:@"MX"];        
    }    
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_HK"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"HK"];
            
        
    }    
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_SI"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"SI"];
        
        
    }  
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_CH"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"CH"];
        
        
    }
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_AX"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"AX"];
        
        
    }  
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_GR"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"GR"];
        
        
    }          
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_PA"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"PA"];
        
        
    }          
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_CN"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"CN"];
        
        
    }           
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_PA"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"PA"];
        
        
    }   
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_GR"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"GR"];
        
        
    }      
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_AX"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"AX"];
        
        
    }           
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_UK"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"UK"];
        
        
    }      
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_ETF"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"ETF"];
        
        
    }               
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_SI"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"SI"];
        
        
    }         
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_US"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"US"];
        
        
    } 
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_INDIA"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"INDIA"];
        
        
    }              
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_INDIA"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"INDIA"];
        
        
    }   
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_NZ"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"NZ"];
        
        
    }         
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_NZ"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"NZ"];
        
        
    }  
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_MI"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"MI"];
        
        
    }              
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_MI"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"MI"];
        
        
    }  
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_SA"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"SA"];
        
        
    }
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_SA"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"SA"];
        
        
    } 
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPad_MX"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"MX"];
        
        
    }    
    else if([DisplayName isEqualToString:@"2D_BASIC_LF_iPhone_MX"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"MX"];
        
        
    }   
    else if([DisplayName isEqualToString:@"2D_BASIC_MESA_iPhone_Global"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        [all_search_country addObject:@"CH"];
        [all_search_country addObject:@"US"];
        [all_search_country addObject:@"HK"];
       // [all_search_country addObject:@"TW"];
        [all_search_country addObject:@"KS"];
        [all_search_country addObject:@"CN"];  
        [all_search_country addObject:@"UK"];  
        [all_search_country addObject:@"SI"];   
        [all_search_country addObject:@"AX"]; 
        [all_search_country addObject:@"GR"]; 
        [all_search_country addObject:@"PA"]; 
        [all_search_country addObject:@"INDIA"];          
        [all_search_country addObject:@"IND"];  
        [all_search_country addObject:@"MI"];         
        [all_search_country addObject:@"NZ"]; 
        [all_search_country addObject:@"SA"];   
        [all_search_country addObject:@"MX"];           
    }
    else if([DisplayName isEqualToString:@"2D_Basic_MESA_Universal_AX"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"AX"];
        
        
    }         
    else if([DisplayName isEqualToString:@"2D_Basic_MESA_Universal_UK"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"UK"];
        
        
    }          
    else if([DisplayName isEqualToString:@"2D_Basic_MESA_Universal_US"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"US"];
        
        
    }         
    else if([DisplayName isEqualToString:@"2D_Basic_MESA_Universal_HK"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"HK"];
        
        
    }           
    else if([DisplayName isEqualToString:@"2D_Basic_MESA_Universal_CH"]  ) {
        //所有可以搜懸的國家
        all_search_country=[[NSMutableArray alloc] init];
        
        [all_search_country addObject:@"CH"];
        
        
    }          
    
	 //管理者增加基金
	if ([[prefs objectForKey:@"isManager"] boolValue]==YES) {
		[all_search_country addObject:@"FU"];	
	}
	
	
	
	
}
#pragma mark -
#pragma mark  設定值畫面
-(void)showSetup{
	
    NSLog(@"showSetup");
    addStockInWatchListSetUp *controller = [[addStockInWatchListSetUp alloc] initWithallcountry:all_search_country];
	controller.delegate = self;
	controller.modalTransitionStyle =UIModalTransitionStyleFlipHorizontal; // 	 
	
  
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){ 
        
       if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ){
           
            //垂直
           controller.AppleDeglate=AppleDeglate;            
          //主圖消失            
            [[(AppDelegate * )AppleDeglate Master_popController]  dismissPopoverAnimated:YES]; 
           
            //顯示購買視窗
            controller.modalPresentationStyle=UIModalPresentationFormSheet;
            [self presentModalViewController:controller animated:YES];              
            
            /*
            ST.AppleDeglate=AppleDeglate; 
            //主圖消失
                             
            //顯示購買視窗
            ST.modalPresentationStyle=UIModalPresentationFormSheet;
            [self presentModalViewController:ST animated:YES];                         
            */
            
            
            
        }
        else{
            //水平
            NSLog(@"aa1");
            if ([popController isPopoverVisible]==NO) {
                NSLog(@"showSetup_水平");
                popController = [[UIPopoverController alloc] initWithContentViewController:controller];
                
                controller.delegate_UIPopoverController=popController;
                
                popController.popoverContentSize = CGSizeMake(320,480);
                [popController presentPopoverFromBarButtonItem:self.navigationItem.rightBarButtonItem  permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; 
            }
                                
            
            
        }
        
        
        
        
        
        
    }               
    else{
        [self presentModalViewController:controller animated:YES];
        
        
    }                   
    
    
    
    
         
    
    
    
	 [controller release];
}
- (void)aflipsideViewControllerDidFinish:(addStockInWatchListSetUp *)controller {
    

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
         [self dismissModalViewControllerAnimated:YES];   
    }        
    else{
    	[self dismissModalViewControllerAnimated:YES];    
    }
    
    
	//要重新再會入表格資料依次
	[self loadView];
}
- (void)InAppPurchase_flipsideViewControllerDidFinish:(InAppPurchase *)controller{
	
	[self dismissModalViewControllerAnimated:YES];
	//要重新再會入表格資料依次
	[self loadView];
}

#pragma mark -
#pragma mark 畫面進入與消失 
- (void)loadView {
	NSLog(@"!!!!- (void)loadView");    
     searchArray_online_code=[[NSMutableArray alloc] init];    
     searchArray_online_name=[[NSMutableArray alloc] init];    
     searchArray_online_id_class=[[NSMutableArray alloc] init];
     searchArray_online_exchange=[[NSMutableArray alloc] init];
    
    [self Setup_DefaultValue];
	
	//取出要搜懸的國家
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	
	search_country=[[NSMutableArray alloc] init];
	search_country=[prefs objectForKey:@"Search Country"];	
		
	
	searchArrayN=[[NSMutableArray alloc] init];
	searchArrayC=[[NSMutableArray alloc] init];
	searchArrayIC=[[NSMutableArray alloc] init];
	all_code=[[NSMutableArray alloc] init];
	all_name=[[NSMutableArray alloc] init];	
	all_id_class=[[NSMutableArray alloc] init];
	for (NSString *country in search_country) {
		[self datasql_code_name:country];
	}
	
	 	
	
	UIView *mainview;
	mainview=[[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
	self.view=mainview;
    [mainview release];
    
	self.view.backgroundColor=[UIColor lightTextColor];	
	
	     
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        
        myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 40.0f, 320.0f, 760.0f)  style:UITableViewStylePlain]; 
    }    
	else{
        
        myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 40.0f, 320.0f, self.view.frame.size.height)  style:UITableViewStylePlain]; 
    }
    
    //線上搜尋
    NSArray *textoptionarray=[NSArray arrayWithObjects: NSLocalizedString(@"Fixed",@"固定"), NSLocalizedString(@"Editable",@"可編輯"),nil]; 
   
   
    segmetnctl=[[UISegmentedControl alloc] initWithItems:textoptionarray];
    [segmetnctl  addTarget:self action:@selector(segmentChanged) forControlEvents:UIControlEventValueChanged];
    segmetnctl.frame=CGRectMake(20,  5, 280, 30);	    
    segmetnctl.selectedSegmentIndex=0;
    [self.view  addSubview:segmetnctl];
    
     self.view.backgroundColor=[UIColor whiteColor];
    
    
    
     myTable.dataSource = self;	
	  myTable.delegate=self;	 
	 [self.view addSubview:myTable];
	  [myTable reloadData];
	
	
	 search = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 280.0f, 44.0f)];
	 search.delegate = self;
	 
	 
	if ([prefs  boolForKey:@"Search By Name" ]==YES){
	   search.placeholder =NSLocalizedString(@"Symbol or Name",@"Symbol or Name") ;	
	}
	else {
	   search.placeholder =NSLocalizedString(@"Symbol",@"Symbol") ;
	}

	
	 
	
	
	search.autocorrectionType = UITextAutocorrectionTypeNo;
	 search.autocapitalizationType = UITextAutocapitalizationTypeNone;
	 self.navigationItem.titleView = search;
	 [search release];
	
	// "Search" is the wrong key usage here. Replacing it with "Done"
	 UITextField *searchField = [[search subviews] lastObject];
	 [searchField setReturnKeyType:UIReturnKeyDone];	
	
	 
}
-(void)viewWillDisappear:(BOOL)animated{
	NSLog(@"!!!!-(void)viewWillDisappear:(BOOL)animated ");
    [self.delegate addStockInWatchLisControllerDidFinish:self];
	

}

#pragma mark -
#pragma mark 切換線上搜尋 


-(void)segmentChanged{
      
    if (segmetnctl.selectedSegmentIndex==0) {
        NSLog(@"Offline");
        		
       
    } 
    else  if (segmetnctl.selectedSegmentIndex==1) {
        NSLog(@"Online");    
              
        
    }  
    search.text=@"";
    [myTable reloadData]; 	
} 


#pragma mark -
#pragma mark 搜尋事件啓動之後進行計算 
- (void) buildSearchArrayFrom: (NSString *) matchString{
	 
	NSString *upString =[matchString uppercaseString]; //[matchString uppercaseString];	
	/*
    //清除搜尋內容
	for (int i=0; i< [search_country count]; i++) {
		[[searchArrayC objectAtIndex:i] release];
		[[searchArrayN objectAtIndex:i] release];
		[[searchArrayIC objectAtIndex:i] release];		
	}
	*/
    
	[searchArrayC removeAllObjects];
	[searchArrayN removeAllObjects];	
	[searchArrayIC removeAllObjects];	
		
	
	if ([matchString length] == 0) {
	 	 
		
		for (int i=0; i< [search_country count]; i++) {
			 [searchArrayC addObject: [all_code objectAtIndex:i]   ];
			 [searchArrayN addObject: [all_name objectAtIndex:i]   ];
			 [searchArrayIC addObject: [all_id_class objectAtIndex:i]   ];
		} 
		
		
		[myTable reloadData];
		return;
	}
	for (int i=0; i< [search_country count]; i++) {
		NSMutableArray *temp_all_code;
		NSMutableArray *temp_all_name;
		NSMutableArray *temp_all_id_class;
		temp_all_code=[[[NSMutableArray alloc] init] autorelease];
		temp_all_name=[[[NSMutableArray alloc] init] autorelease];
		temp_all_id_class=[[[NSMutableArray alloc] init] autorelease];
		[searchArrayC addObject: temp_all_code ];
		[searchArrayN addObject: temp_all_name  ];
		[searchArrayIC addObject: temp_all_id_class  ];		
	}		
	
	 
	
	//搜尋代碼================
	for (int i=0; i< [search_country count]; i++) {
		 
		for (NSString *word in [all_code objectAtIndex:i])
		{
			
			
			NSRange range = [ word   rangeOfString:upString];
			if (range.location != NSNotFound){
				
				int index;
				index=[[all_code objectAtIndex:i] indexOfObject:word];			
				[[searchArrayN objectAtIndex:i] addObject: [[all_name objectAtIndex:i] objectAtIndex:index] ];
				[[searchArrayIC objectAtIndex:i] addObject: [[all_id_class objectAtIndex:i] objectAtIndex:index]  ];
				
				
				[[searchArrayC objectAtIndex:i] addObject:  word     ];
				
			}
			
			
		}
		
		
		
		
	} 	
	
	 
	//搜尋 名稱================
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	if ([prefs  boolForKey:@"Search By Name" ]==YES){
		for (int i=0; i< [search_country count]; i++){
			for (NSString *word in [all_name objectAtIndex:i])
			{
				
				
				NSRange range = [ word   rangeOfString:upString];
				if (range.location != NSNotFound){
					
					int index;
					index=[[all_name objectAtIndex:i] indexOfObject:word];			
					
					//檢查代碼與名稱是否有重複 這只有英語體系代碼與名稱有可能相同之下會發生
					if([[searchArrayN objectAtIndex:i] indexOfObject:word]==2147483647){			
						[[searchArrayC  objectAtIndex:i] addObject: [[all_code  objectAtIndex:i] objectAtIndex:index]  ];
						[[searchArrayIC  objectAtIndex:i] addObject: [[all_id_class  objectAtIndex:i] objectAtIndex:index]  ];
						
						[[searchArrayN objectAtIndex:i] addObject: word   ];	
					}
					
				}
				
				
			}			
		
		}		
		
		
 
	
	}
	 
	[myTable reloadData];
	 
}
// When the search text changes, update the array
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (segmetnctl.selectedSegmentIndex==0) {
        NSLog(@"點擊 非線上搜尋");
        [self buildSearchArrayFrom:searchText];
        if ([searchText length] == 0) [searchBar resignFirstResponder];
        
        
    } 
    else  if (segmetnctl.selectedSegmentIndex==1) {
        NSLog(@"點擊 線上搜尋=%@",searchText); 
        
        NSString *urls=[NSString stringWithFormat: @"http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=%@&callback=YAHOO.Finance.SymbolSuggest.ssCallback",searchText] ;        
        
        
        NSURL *  urla;
        urla = [NSURL URLWithString:urls];
        
        NSError * errorq = nil;
        NSString * download_string;
        download_string=[NSString stringWithContentsOfURL:urla encoding:NSUTF8StringEncoding error:&errorq];
        
        NSLog(@"下載原始字串=%@",download_string);
        
        //去除無用的字串 '//'
        NSString *string_for_jsonvalue= [[download_string stringByReplacingOccurrencesOfString: @"YAHOO.Finance.SymbolSuggest.ssCallback(" withString:@"" ] stringByReplacingOccurrencesOfString:@")" withString:@""];
        
        //***JSONValue 巢狀******************************* 
        NSDictionary *jsonvalue_elements = [[[string_for_jsonvalue JSONValue] objectForKey:@"ResultSet"] objectForKey:@"Result"];
        
        [searchArray_online_code removeAllObjects];
        [searchArray_online_name removeAllObjects];        
        [searchArray_online_id_class removeAllObjects];  
        [searchArray_online_exchange removeAllObjects];  
        
        for (NSDictionary *sss in jsonvalue_elements ) {
            NSLog(@"exch=%@",[sss objectForKey:@"exch"]  );
            NSLog(@"exchDisp=%@",[sss objectForKey:@"exchDisp"]  ); 
            NSLog(@"name=%@",[sss objectForKey:@"name"]  );         
            
            NSLog(@"symbol=%@",[sss objectForKey:@"symbol"]  );    
            
           
            
            NSLog(@"type=%@",[sss objectForKey:@"type"]  );  
            NSLog(@"typeDisp=%@",[sss objectForKey:@"typeDisp"]  );          
            
            [searchArray_online_code addObject: [sss objectForKey:@"symbol"] ];            
            [searchArray_online_name addObject:[sss objectForKey:@"name"] ];
            [searchArray_online_id_class addObject:[sss objectForKey:@"typeDisp"]];
            if ([sss objectForKey:@"exchDisp"]==nil) {
                [searchArray_online_exchange addObject:[sss objectForKey:@"exch"] ]; 
            }
            else{
               [searchArray_online_exchange addObject:[sss objectForKey:@"exchDisp"] ]; 
            }
                       
        }        
        
        
                 
        
        
        
        [myTable reloadData];
        
        
    }          
    
  
}

// When the search button (i.e. "Done") is clicked, hide the keyboard
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
	
    [searchBar resignFirstResponder];
    
}

#pragma mark -
#pragma mark  讀取資料
-(void)datasql_code_name:(NSString *) country{
	
	//從資料庫取出資料
	const char *sql = NULL;	
	//設定要執行篩選的ＳＬＱ敘述
	NSMutableArray *temp_all_code;
	NSMutableArray *temp_all_name;
	NSMutableArray *temp_all_id_class;	
    NSString *tsql;
	
	tsql=@"SELECT id,Symbol,Lname,Ename,Class FROM ";
	tsql=[tsql stringByAppendingString:country];
	sql=[tsql UTF8String];
	 
	temp_all_code=[[[NSMutableArray alloc] init] autorelease];
	temp_all_name=[[[NSMutableArray alloc] init] autorelease];
	temp_all_id_class=[[[NSMutableArray alloc] init] autorelease];
	
    NSString *ver;
	ver=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
	ver=[ver stringByReplacingOccurrencesOfString:@"." withString:@"_"];
	NSString *filename;
	filename=@"data_";
	filename=[filename stringByAppendingString:ver];
	NSString *filenamexx;
	filenamexx=@"sqlite3";
	NSString *fullfilename;
	fullfilename=[filename stringByAppendingString:@"."];
	fullfilename=[fullfilename stringByAppendingString:filenamexx];
	DBHelper *helper =[DBHelper newInstance:filename andEXT:filenamexx andfullname:fullfilename];
	
	
	
	
	
	sqlite3 *database = [helper openDatabase]; 
	sqlite3_stmt *stm;
	
	if(sqlite3_prepare_v2(database, sql, strlen(sql), &stm, NULL)== SQLITE_OK) {
		
		while(sqlite3_step(stm) ==SQLITE_ROW)
		{
			 
			 
				char *field1=(char *)sqlite3_column_text(stm, 1);
				NSString *ss1=[[NSString alloc]initWithUTF8String:field1];
				[temp_all_code addObject:ss1];				
                [ss1 release];
			
			//2:名稱
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs  boolForKey:@"localize Name" ];
			
			if ((BOOL)[prefs  boolForKey:@"localize Name" ]==YES) {
				//表示使用當地語言的名稱
				char *field2=(char *)sqlite3_column_text(stm, 2);
				NSString *ss2=[[NSString alloc]initWithUTF8String:field2];
				[temp_all_name addObject:ss2];	
                [ss2 release];
			} 
			else {
				//表示採用英語當作名稱
				char *field2=(char *)sqlite3_column_text(stm, 3);
				NSString *ss2=[[NSString alloc]initWithUTF8String:field2];
				[temp_all_name addObject:ss2];
                [ss2 release];
			}
 		
			//分類
			char *field4=(char *)sqlite3_column_text(stm, 4);
			NSString *ss4=[[NSString alloc]initWithUTF8String:field4];
			[temp_all_id_class addObject:ss4];			
			[ss4 release];
			
									
			 
			
			
			
			
		}
		//code_array=tcode_array;
	}
	//結束查詢作業
	sqlite3_finalize(stm);
	 
	[all_code addObject: temp_all_code ];
	[searchArrayC addObject:  temp_all_code ];
	[all_name addObject:  temp_all_name  ];
	[searchArrayN addObject: temp_all_name  ];
	[all_id_class addObject: temp_all_id_class  ];
	[searchArrayIC addObject: temp_all_id_class  ];	
	 /*
    [all_code addObject: temp_all_code  ];
	[searchArrayC addObject: temp_all_code  ];
	[all_name addObject: temp_all_name   ];
	[searchArrayN addObject: temp_all_name  ];
	[all_id_class addObject: temp_all_id_class ];
	[searchArrayIC addObject: temp_all_id_class  ];	    
    */
	 	
}
#pragma mark -
#pragma mark  表格 表頭
 



#pragma mark -
#pragma mark  表格 功能選項

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (segmetnctl.selectedSegmentIndex==0) {
       return [[searchArrayC objectAtIndex:section] count];
        
        
    } 
    else  if (segmetnctl.selectedSegmentIndex==1) {
        return [searchArray_online_code  count]; 
        
        
    }        
    else{
        return 0;
    
    }
    
	
	 
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	//取出要搜懸的國家
   
    if (segmetnctl.selectedSegmentIndex==0) {
         return   [search_country count];
        
        
    } 
    else  if (segmetnctl.selectedSegmentIndex==1) {
        return 1; 
        
        
    }        
    else{
        return 1;
        
    }
    
    
    
    
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
	
    
    if (segmetnctl.selectedSegmentIndex==0) {
        NSMutableArray *aa;
        aa=[[[NSMutableArray alloc] init] autorelease];
        
        for (NSString *coutry in search_country) {
            [aa addObject:NSLocalizedString(coutry,coutry)];
        }
        [aa addObject:@""];
        return aa;
        
        
    } 
    else  if (segmetnctl.selectedSegmentIndex==1) {
        return nil; 
        
        
    }        
    else{
        return nil;
        
    }
    
    
    
    
    
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    
    
    
    
	 NSString *title = nil;
    
    if (segmetnctl.selectedSegmentIndex==0) {
        title = [NSLocalizedString([search_country objectAtIndex:section ],[search_country objectAtIndex:section ]) stringByAppendingFormat:@"(%i),%@=%i " ,[[searchArrayC objectAtIndex:section ]count],NSLocalizedString(@"Total symbols","Total symbols"),[watchlist_code count ]];
        
    } 
    else  if (segmetnctl.selectedSegmentIndex==1) {
        
        title=@"Search";
        
    }        
    else{
        
        
    }

 	
	return title;	
	
	
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	 
	static NSString *CellIdentifier = @"TableCellAddStockWatchList";
    
    TableCellAddStockWatchList *cell =(TableCellAddStockWatchList *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   
	if (cell == nil) {
        cell = [[[TableCellAddStockWatchList alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    if (segmetnctl.selectedSegmentIndex==0) {
        
        //標記:是否移除交易所碼        
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	
        
        if ([[prefs objectForKey:@"isRemoveExchangeCode"] boolValue]==YES) {
            //字串分割
            NSArray *code_exchange_Array = [[[searchArrayC objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]  componentsSeparatedByString:@"."];
            if ([code_exchange_Array count]==2) {
                cell.code.text=[code_exchange_Array objectAtIndex:0];
                
                //標記:檢視第一個字串是否等於某這字
                
                NSString *temp = @"^";            
                if([temp characterAtIndex:0] == [[code_exchange_Array objectAtIndex:0] characterAtIndex:0] ){
                    cell.exchange.text=@"Index";          
                }            
                else{
                    ExchangeClass *tempe;
                    tempe=[[ExchangeClass alloc] init];
                    cell.exchange.text=  [tempe Get_exchange_fullname:[code_exchange_Array objectAtIndex:1]];
                    [tempe release];             
                    
                }
                
                
                
                
            }
            else{
                NSString *temp = @"^";            
                
                if([temp characterAtIndex:0] == [[code_exchange_Array objectAtIndex:0] characterAtIndex:0] ){
                    cell.exchange.text=@"Index";          
                }            
                else{
                    cell.code.text = [[searchArrayC objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] ;         
                    
                    ExchangeClass *tempe;
                    tempe=[[ExchangeClass alloc] init];
                    cell.exchange.text=  [tempe Get_exchange_fullname:[code_exchange_Array objectAtIndex:0]];
                    [tempe release];             
                    
                }
                
                
                
                
            }
            
            
            
        }
        else {
            cell.code.text = [[searchArrayC objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] ;
        }                
        //將代碼隱藏至code_add    
        cell.code_add.text=[[searchArrayC objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] ; 
        
        
        
        //cell.code_exchange_Array
        //cell.code.text = [[searchArrayC objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] ;    
        
        
        cell.name.text=[[searchArrayN objectAtIndex:indexPath.section]  objectAtIndex:indexPath.row];	
        cell.id_class.text=[[searchArrayIC objectAtIndex:indexPath.section]  objectAtIndex:indexPath.row];	 
        //檢查是否已經納入自選股中
	 	
        if(  !([watchlist_code indexOfObject:cell.code_add.text]==2147483647) )	
        {
            cell.accessoryType=UITableViewCellAccessoryCheckmark;
            cell.code.textColor=[UIColor blueColor];
            cell.name.textColor=[UIColor blueColor];
            cell.id_class.textColor=[UIColor blueColor];	
            cell.exchange.textColor=[UIColor blueColor];        
        }
        else {
            cell.accessoryType=UITableViewCellAccessoryNone;
            cell.code.textColor=[UIColor blackColor];
            cell.name.textColor=[UIColor blackColor];	
            cell.id_class.textColor=[UIColor blackColor];
            cell.exchange.textColor=[UIColor blackColor];        
            
        }
        
        cell.name_edit.hidden=YES;
        cell.id_class_edit.hidden=YES;        
        
        
    } 
    else if (segmetnctl.selectedSegmentIndex==1) {
        
        cell.delgete=self;
        
        cell.name_edit.hidden=NO;
        cell.id_class_edit.hidden=NO;
        
        
        cell.name.hidden=YES;
        cell.id_class.hidden=YES;
        
        //標記:是否移除交易所碼        
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        if ([[prefs objectForKey:@"isRemoveExchangeCode"] boolValue]==YES) {
            //字串分割
            NSArray *code_exchange_Array_edit = [ [searchArray_online_code objectAtIndex:indexPath.row] componentsSeparatedByString:@"."];            
            cell.code.text =[code_exchange_Array_edit objectAtIndex:0];
        
        }
        else{
           cell.code.text =[searchArray_online_code objectAtIndex:indexPath.row];        
        }
       
        
        
        cell.code_add.text=[searchArray_online_code objectAtIndex:indexPath.row];        
        cell.name.text =[searchArray_online_name objectAtIndex:indexPath.row];
        
        NSUInteger index;
        index=[watchlist_code indexOfObject:cell.code_add.text]  ;
       
        if (index==NSNotFound) {
             cell.name_edit.text=[searchArray_online_name objectAtIndex:indexPath.row];
             cell.id_class_edit.text=[searchArray_online_id_class objectAtIndex:indexPath.row];
                        
        }
        else{
            cell.name_edit.text=[watchlist_name objectAtIndex:index];
            cell.id_class_edit.text=[watchlist_id_class objectAtIndex:index];            
            
        
        }
       
        
        cell.id_class.text =[searchArray_online_id_class objectAtIndex:indexPath.row];	
        cell.exchange.text =[searchArray_online_exchange objectAtIndex:indexPath.row];         
        
        if(  !([watchlist_code indexOfObject:cell.code_add.text]==2147483647) )	
        {
            cell.accessoryType=UITableViewCellAccessoryCheckmark;
            cell.code.textColor=[UIColor blueColor];
            cell.name.textColor=[UIColor blueColor];
            cell.id_class.textColor=[UIColor blueColor];	
            cell.exchange.textColor=[UIColor blueColor];        
        }
        else {
            cell.accessoryType=UITableViewCellAccessoryNone;
            cell.code.textColor=[UIColor blackColor];
            cell.name.textColor=[UIColor blackColor];	
            cell.id_class.textColor=[UIColor blackColor];
            cell.exchange.textColor=[UIColor blackColor];        
            
        }
        
        
        
    }        
    else{
        
        
    }   
    
	
    return cell;
	
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	//鍵盤消失  
	[search resignFirstResponder];
	 
	
	 TableCellAddStockWatchList *cell=(TableCellAddStockWatchList *)[myTable cellForRowAtIndexPath:indexPath];
	
    
     if (cell.accessoryType==UITableViewCellAccessoryNone) {
		 //MaxSymbolsWatchlist		 
		 NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
		 
         //標記:限制自選群組可以使用的檔數
         int maxsymblos;
		 maxsymblos=[[prefs objectForKey:@"MaxSymbolsWatchlist" ] intValue ];
	
         BOOL isAuto_Renewable_Subscriptions;
         
         if ([[prefs objectForKey:@"iap_type" ] isEqualToString:@"Auto-Renewable Subscriptions"]) {
             isAuto_Renewable_Subscriptions=YES;   
         }
         else{
             isAuto_Renewable_Subscriptions=NO;
         }
         
         if (maxsymblos>  [watchlist_code count] || isAuto_Renewable_Subscriptions==YES) {
			 //如果檔數尚未超過 或是採用自動續約則可以加入檔數 自動續約是用別種方式管制
			                
             
			 [watchlist_code addObject:cell.code_add.text];
             //修改股票名稱
             if (segmetnctl.selectedSegmentIndex==0){
                [watchlist_name addObject:cell.name.text];
                [watchlist_id_class addObject:cell.id_class.text];                 
             }
              else if (segmetnctl.selectedSegmentIndex==1) {
                 [watchlist_name addObject:cell.name_edit.text];
                 [watchlist_id_class addObject:cell.id_class_edit.text];                    
             }                
            
			 
			 
             
			 cell.code.textColor=[UIColor blueColor];
			 cell.name.textColor=[UIColor blueColor];	
			 cell.id_class.textColor=[UIColor blueColor];				 
			 
			 
		 } 		 
		 else {
			 
			 UIAlertView *ia;
			
			 NSString *titles;
			 titles=NSLocalizedString(@"Each Watchlist is limit to",@"Each Watchlist is limit to");
			 titles=[titles stringByAppendingFormat:@" %i ",maxsymblos];
			 titles=[titles stringByAppendingString:NSLocalizedString(@"symbols now!",@"symbols now!")];
			 
			 ia=[[UIAlertView alloc] initWithTitle:titles message:NSLocalizedString( @"Would you want to add more symbols in your watchlist?",@"你想要提高每個自選股群組的最大檔數限制嗎?") delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES",nil];
			 [ia show];	
			 [ia release];
			 
			 
		 }

		 	 
		 
	 }
	 else {
		 
		// cell.accessoryType= UITableViewCellAccessoryNone;
		 NSLog(@"WWWWWWWWWWWWWWWWWWWWWWWWWW");
         NSUInteger index;
         
         index=[watchlist_code indexOfObject:cell.code_add.text];
         
         [watchlist_code removeObjectAtIndex:index];
         [watchlist_name removeObjectAtIndex:index];
		 [watchlist_id_class removeObjectAtIndex:index];		 
		
         cell.code.textColor=[UIColor blackColor];
		 cell.name.textColor=[UIColor blackColor];		 
		 cell.id_class.textColor=[UIColor blackColor];		 
	 }
	 
	[myTable reloadData];
	      
 }
 
#pragma mark -
#pragma mark  table cell修改名字後的動作
-(void)edit_name_done_code:(NSString *)code ename:(NSString *)name eid_class:(NSString *) id_class{
    NSUInteger index;
    index=[watchlist_code indexOfObject:code];    
    if (index!=NSNotFound) {
        [watchlist_name replaceObjectAtIndex:index withObject:name];
        [watchlist_id_class replaceObjectAtIndex:index withObject:id_class];        
    }
    NSLog(@"edit_name_done code=%@ name=%@ ",code,name);

}

#pragma mark -
#pragma mark  其他

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];


}


- (void)dealloc {
    NSLog(@"dealloc_addStockInWatchList");
  
    [all_code release ];
	[searchArrayC release  ];
	[all_name release   ];
	[searchArrayN release  ];
	[all_id_class release ];
	[searchArrayIC release ];	      
    
    
    
    
    [super dealloc];
	 	
	  
	
	
	
	
}
#pragma mark -
#pragma mark  是否要增加自選股數目
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	
    switch (buttonIndex) {
        case 0:
            NSLog(@"Cancel Button Pressed");
            break;
        case 1:{
			//表示要增加自選股數目
			NSLog(@"要增加自選股數目");
			             
			InAppPurchase *ST;
			ST=[[InAppPurchase alloc] initAddStockWatchlist];
			
			if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){ 
                 
                if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ) {
                    //垂直
                    
                    ST.AppleDeglate=AppleDeglate; 
                    //主圖消失
                    [[(AppDelegate * )AppleDeglate Master_popController]  dismissPopoverAnimated:YES];                    
                    //顯示購買視窗
                    ST.modalPresentationStyle=UIModalPresentationFormSheet;
                    [self presentModalViewController:ST animated:YES];                         
                    
                }
                else{
                    NSLog(@"iPad-水平-IAP");
                    //水平
                    /*原本
                    UIPopoverController* apopController = [[UIPopoverController alloc] initWithContentViewController:ST];
                    ST.delegate_UIPopoverController=apopController;
                    popController.popoverContentSize = CGSizeMake(320,460);
                    [popController presentPopoverFromBarButtonItem:self.navigationItem.rightBarButtonItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];                     
                    */
                    //修正顯示購買視窗
                    ST.modalPresentationStyle=UIModalPresentationFormSheet;
                    [self presentModalViewController:ST animated:YES];                      
                    
                }
                
                
                
                
                
                
            }               
            else{
                ST.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal; 
                [self presentModalViewController:ST animated:YES];
                
                
            }                   
            
            
            
            ST.delegate=self;
			[ST release];
			
            break;
		}
        
        default:
            break;
    }
	
}

@end
